// 📡 获取用户数据消息处理器
import type { PlasmoMessaging } from "@plasmohq/messaging"

// 类型定义
type GetUserDataRequest = { userId: number; includeSettings?: boolean }
type UserSettings = { theme: 'light' | 'dark' | 'auto'; language: string; notifications: boolean; privacy: { showEmail: boolean; showProfile: boolean } }
type UserProfile = { id: number; name: string; email: string; avatar?: string; settings?: UserSettings; lastLogin: string }
type ApiResponse<T = any> = { success: boolean; data?: T; error?: { code: string; message: string; details?: any } }

const ErrorCodes = {
  UNKNOWN_ERROR: 'UNKNOWN_ERROR',
  INVALID_REQUEST: 'INVALID_REQUEST', 
  UNAUTHORIZED: 'UNAUTHORIZED',
  INSUFFICIENT_PERMISSIONS: 'INSUFFICIENT_PERMISSIONS',
  USER_NOT_FOUND: 'USER_NOT_FOUND',
  VALIDATION_ERROR: 'VALIDATION_ERROR',
  NETWORK_ERROR: 'NETWORK_ERROR',
  TIMEOUT_ERROR: 'TIMEOUT_ERROR'
} as const

// 模拟用户数据库
const mockUsers: Record<number, UserProfile> = {
  123: {
    id: 123,
    name: "张三",
    email: "zhangsan@example.com",
    avatar: "https://api.dicebear.com/7.x/avataaars/svg?seed=zhangsan",
    settings: {
      theme: "dark",
      language: "zh-CN",
      notifications: true,
      privacy: {
        showEmail: false,
        showProfile: true
      }
    },
    lastLogin: new Date().toISOString()
  },
  456: {
    id: 456,
    name: "李四",
    email: "lisi@example.com",
    avatar: "https://api.dicebear.com/7.x/avataaars/svg?seed=lisi",
    settings: {
      theme: "light",
      language: "en-US",
      notifications: false,
      privacy: {
        showEmail: true,
        showProfile: true
      }
    },
    lastLogin: new Date(Date.now() - 86400000).toISOString() // 1天前
  }
}

/**
 * 获取用户数据处理器
 * 
 * @param req - 包含 userId 和可选的 includeSettings 的请求
 * @param res - 响应对象
 */
const handler: PlasmoMessaging.MessageHandler<GetUserDataRequest, ApiResponse<UserProfile>> = async (req, res) => {
  console.log("📨 收到获取用户数据请求:", req.body)
  
  try {
    const { userId, includeSettings = true } = req.body
    
    // 验证请求参数
    if (!userId || typeof userId !== 'number') {
      res.send({
        success: false,
        error: {
          code: ErrorCodes.INVALID_REQUEST,
          message: "用户ID无效",
          details: "userId 必须是一个有效的数字"
        }
      })
      return
    }
    
    // 模拟数据库查询延迟
    await new Promise(resolve => setTimeout(resolve, 200))
    
    // 查找用户
    const user = mockUsers[userId]
    if (!user) {
      res.send({
        success: false,
        error: {
          code: ErrorCodes.USER_NOT_FOUND,
          message: "用户不存在",
          details: `找不到ID为 ${userId} 的用户`
        }
      })
      return
    }
    
    // 根据请求决定是否包含设置
    const userData: UserProfile = {
      ...user,
      settings: includeSettings ? user.settings : undefined
    }
    
    res.send({
      success: true,
      data: userData
    })
    
    console.log("📤 发送用户数据:", { userId, includeSettings })
    
  } catch (error) {
    console.error("❌ 获取用户数据错误:", error)
    res.send({
      success: false,
      error: {
        code: ErrorCodes.UNKNOWN_ERROR,
        message: "获取用户数据时发生错误",
        details: error.message
      }
    })
  }
}

export default handler